import java.util.function.IntConsumer;

public class t1116 {
    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(9);
        Thread t1 = new Thread(
                () -> {
                    try {
                        zeroEvenOdd.zero(System.out::print);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        );
        Thread t2 = new Thread(
                () -> {
                    try {
                        zeroEvenOdd.even(System.out::print);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        );
        Thread t3 = new Thread(
                () -> {
                    try {
                        zeroEvenOdd.odd(System.out::print);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        );
        t1.start();
        t2.start();
        t3.start();
    }

}

class ZeroEvenOdd {
    private int n;
    private int num = 0;

    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (this) {
                while ((num & 1) == 1) {
                    this.wait();
                }
                num++;
                printNumber.accept(0);
                notifyAll();
            }
        }


    }

    public void even(IntConsumer printNumber) throws InterruptedException {

        for (int i = 2; i <= n; i += 2) {
            synchronized (this) {
                while ((num & 1) == 0 || num % 4 != 3) {
                    this.wait();
                }
                num++;
                printNumber.accept(i);
                notifyAll();
            }
        }

    }

    public void odd(IntConsumer printNumber) throws InterruptedException {

        for (int i = 1; i <= n; i += 2) {
            synchronized (this) {
                while ((num & 1) == 0 || num % 4 != 1) {
                    this.wait();
                }
                num++;
                printNumber.accept(i);
                notifyAll();
            }
        }
    }
}
